package com.yunyao.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.yunyao.common.dto.PurchaseDto;
import com.yunyao.common.dto.excel.ContractExcelDto;
import com.yunyao.common.dto.excel.ContractMaterialExcelDto;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.framework.dto.contract.ContractMaterialImportDto;
import com.yunyao.framework.dto.file.FileInfoDto;
import com.yunyao.framework.dto.purchase.PurchaseContractApprovalDto;
import com.yunyao.framework.dto.purchase.PurchaseContractDeletedDto;
import com.yunyao.framework.dto.purchase.PurchaseContractSaveDto;
import com.yunyao.framework.dto.purchase.PurchaseContractSubmitApprovalDto;
import com.yunyao.framework.service.PurchaseService;
import com.yunyao.framework.vo.purchase.PurchaseInfoVO;
import com.yunyao.framework.vo.purchase.PurchaseVO;
import com.yunyao.web.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author xingjishuai
 * @date 2024-07-22
 */
@RestController
@RequestMapping("/purchase")
@Slf4j
public class PurchaseController {
    @Autowired
    private PurchaseService purchaseService;

    /**
     * 获取采购合同列表
     *
     * @param purchaseDto
     * @return
     */
    @GetMapping("/list")
    public YResult<PageResult<PurchaseVO>> pageList(PurchaseDto purchaseDto) {
        return purchaseService.pageList(purchaseDto);
    }

    /**
     * 获取采购合同详情
     *
     * @param id
     * @return
     */
    @GetMapping("/info")
    public YResult<PurchaseInfoVO> getInfo(String id) {
        return purchaseService.getPurchaseContractById(id);
    }

    /**
     * 保存采购合同
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/save")
    public YResult<String> saveInfo(@RequestBody PurchaseContractSaveDto saveDto) {
        return purchaseService.saveInfo(saveDto);
    }

    /**
     * 删除采购合同信息
     *
     * 此接口用于通过HTTP POST请求处理采购合同的删除操作它依赖于PurchaseService类中的deleted方法，
     * 通过请求体中的采购合同ID来标识要删除的采购合同
     *
     * @param saveDto 包含要删除的采购合同的ID，使用@Validated注解进行数据校验
     * @return YResult类型的对象，包含操作结果信息
     */
    @PostMapping("/deleted")
    public YResult<String> deleted(@RequestBody @Validated PurchaseContractDeletedDto saveDto) {
        return purchaseService.deleted(saveDto.getId());
    }


    /**
     * 提交审批
     *
     * 该接口用于提交采购合同的审批申请通过接收一个包含采购合同信息的对象，
     * 确保采购合同能够按照预定流程进行审批
     *
     * @param approvalDto 采购合同提交审批的详细信息，包括采购合同的各项数据及审批相关信息
     * @return 返回一个包含审批结果的响应对象，结果可能包括成功、失败等信息
     */
    @PostMapping("/submit/approval")
    public YResult<String> submitApproval(@RequestBody @Validated PurchaseContractSubmitApprovalDto approvalDto) {
        return purchaseService.submitApproval(approvalDto);
    }


    @PostMapping("/approval")
    public YResult<String> approval(@RequestBody @Validated PurchaseContractApprovalDto approvalDto) {
        // 调用采购服务的approval方法，委托其处理采购合同审批逻辑
        return purchaseService.approval(approvalDto);
    }

    /**
     * 撤销
     *
     * @return
     */
    @PostMapping("/revocation")
    public YResult<String> revocation() {
        return YResult.error("暂不支持");
    }


    /**
     * 导入材料文件
     *
     * @return
     */
    @PostMapping("/import/material/file")
    public YResult<String> importMaterialFile(@RequestParam("file") MultipartFile file,
                                              @RequestParam("contractId") String contractId) {
        ContractMaterialImportDto importDto = new ContractMaterialImportDto();
        importDto.setFile(file);
        importDto.setContractId(contractId);
        return purchaseService.importContractMaterial(importDto);
    }


    /**
     * 导出材料文件
     *
     * @return
     */

    @GetMapping("/export/material/file")
    public YResult<String> exportMaterialFile(@RequestParam String contractId,@RequestParam String contractNo, HttpServletResponse response) {
        try {
            List<ContractMaterialExcelDto> contractMaterialExportDtoList =  purchaseService.exportMaterial(contractId);
            try {
                // 这里URLEncoder.encode可以防止中文乱码
                String fileName = URLEncoder.encode(contractNo, String.valueOf(StandardCharsets.UTF_8))+".xlsx";
//                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //设置sheet名
                ExportParams params = new ExportParams();
                params.setSheetName("合同材料信息模版");
                //设置标题
//                params.setTitle("商品信息");
                // 这里需要设置不关闭流
                Workbook workbook = ExcelExportUtil.exportExcel(params, ContractMaterialExcelDto.class, contractMaterialExportDtoList);
                //输出流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] bytes = bos.toByteArray();
                bos.close();
                try {
                    FileInfoDto fileInfoDto = AliOssUtil.upload(bytes,
                            fileName, null);
                    if (null != fileInfoDto) {
                        return YResult.success(fileInfoDto.getLink());
                    } else {
                        return YResult.error("连接文件服务器失败，请重试");
                    }
                } catch (Exception e) {
                    return YResult.error("下载失败，请重试");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }catch (Exception e) {
            log.error("导出合同材料失败",e);
        }
        return YResult.error("导出合同材料失败");
    }

    /**
     * 导出文件
     *
     * @return
     */

    @GetMapping("/export/file")
    public YResult<String> exportFile(PurchaseDto purchaseDto, HttpServletResponse response) {
        try {
            List<ContractExcelDto> contractMaterialExportDtoList =  purchaseService.export(purchaseDto);
            try {
                // 这里URLEncoder.encode可以防止中文乱码
                String fileName = URLEncoder.encode("purchaseContract", String.valueOf(StandardCharsets.UTF_8))+".xlsx";
//                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //设置sheet名
                ExportParams params = new ExportParams();
                params.setSheetName("合同信息模版");
                //设置标题
//                params.setTitle("商品信息");
                // 这里需要设置不关闭流
                Workbook workbook = ExcelExportUtil.exportExcel(params, ContractExcelDto.class, contractMaterialExportDtoList);
                //输出流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] bytes = bos.toByteArray();
                bos.close();
                try {
                    FileInfoDto fileInfoDto = AliOssUtil.upload(bytes,
                            fileName, null);
                    if (null != fileInfoDto) {
                        return YResult.success(fileInfoDto.getLink());
                    } else {
                        return YResult.error("连接文件服务器失败，请重试");
                    }
                } catch (Exception e) {
                    return YResult.error("下载失败，请重试");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }catch (Exception e) {
            log.error("导出合同信息失败",e);
        }
        return YResult.error("导出合同信息失败");
    }
}
